package com.timemanage.activity

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.timemanage.R
import com.timemanage.dao.AppDatabase
import com.timemanage.dao.UserDao
import com.timemanage.utils.MyApplication
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_sginup.*
import kotlinx.android.synthetic.main.activity_sginup.signup

class sginupActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sginup)
        var database= AppDatabase.getDatabase(MyApplication.context)
        var userdao: UserDao =database.userDao();
        var users = userdao.selectUser()
        val currentName = ArrayList<String>()
        for(i in users){
            currentName.add(i.useName)
        }
        signup.setOnClickListener {
            var f = 0
            val username = username1.text.toString()
            val password_1 = password1.text.toString()
            val password_2 = password2.text.toString()
            for (i in currentName) {
                if (i == username) {
                    f = 1
                    break
                }
            }
            // != || f!=0
            if (password_1 == password_2 && f == 0) {
                userdao.insertUser(username, password_1, 0)
                val intent = Intent(this, loginActiviy::class.java)
                intent.putExtra("userName", username)
                intent.putExtra("pwd", password_1)
                startActivity(intent)
                finish()
            } else if ( f == 1) {
                Toast.makeText(this, "用户名已存在！", Toast.LENGTH_SHORT).show()
            } else if(password_1 != password_2 ){
                Toast.makeText(this, "两次密码不一致", Toast.LENGTH_SHORT).show()
            }
        }
    }
}